<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2>我的购物车</h2>
      <button class="clear-btn" @click="handleClearCart" :disabled="!cartStore.cartList.length">
        清空购物车
      </button>
    </div>

    <div class="cart-empty" v-if="!cartStore.cartList.length">
      <img src="" alt="购物车为空" class="empty-img" />
      <p>购物车还是空的，快去添加商品吧~</p>
      <router-link to="/" class="go-shopping">去购物</router-link>
    </div>

    <div class="cart-list" v-else>
      <div class="cart-item" v-for="item in cartStore.cartList" :key="item.cart_id">
        <div class="item-checkbox">
          <input
            type="checkbox"
            :checked="item.selected"
            @change="(e) => handleItemSelect(item.cart_id, (e.target as HTMLInputElement).checked)"
          />
        </div>

        <div class="item-image">
          <img
            :src="item.goods_info.goods_cover_img || '/placeholder-product.png'"
            :alt="item.goods_info.goods_name"
          />
        </div>

        <div class="item-info">
          <h3 class="item-name">{{ item.goods_info.goods_name }}</h3>
          <div class="price-info">
            <span class="current-price">¥{{ formatPrice(item.goods_info.goods_price) }}</span>
            <span class="market-price" v-if="item.goods_info.market_price"
              >¥{{ formatPrice(item.goods_info.market_price) }}</span
            >
          </div>

          <div class="item-actions">
            <div class="quantity-control">
              <button @click="handleDecrease(item)" :disabled="item.goods_num <= 1">-</button>
              <input
                type="number"
                v-model.number="item.goods_num"
                @change="handleQuantityChange(item)"
                :min="1"
                :max="item.goods_info.goods_stock"
              />
              <button
                @click="handleIncrease(item)"
                :disabled="item.goods_num >= item.goods_info.goods_stock"
              >
                +
              </button>
            </div>

            <button class="delete-btn" @click="handleRemoveItem(item.cart_id)">删除</button>
          </div>

          <div class="item-status" v-if="!item.goods_info.is_active">
            <span class="inactive-tag">已下架</span>
          </div>
          <div class="item-status" v-else-if="item.goods_num > item.goods_info.goods_stock">
            <span class="stock-tag">库存不足</span>
          </div>
        </div>
      </div>
    </div>

    <div class="cart-footer" v-if="cartStore.cartList.length">
      <div class="total-info">
        <p>已选 {{ cartStore.selectedCount }} 件商品</p>
        <div class="total-price">
          合计: <span>¥{{ cartStore.selectedTotalAmount.toFixed(2) }}</span>
        </div>
      </div>

      <button class="checkout-btn" @click="handleCheckout" :disabled="!cartStore.hasSelectedItems">
        结算
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useCartStore } from '@/stores/useCartStore'
import { formatPrice, type CartItem } from '@/api/cart'
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

// 初始化购物车存储
const cartStore = useCartStore()
const router = useRouter()

// 页面加载时获取购物车数据
onMounted(async () => {
  try {
    await cartStore.fetchCartList()
  } catch (error) {
    console.error('加载购物车失败:', error)
    // ElToast.error('加载购物车失败，请稍后重试')
  }
})

// 监听购物车数据变化，确保计算属性正确更新
watch(
  () => cartStore.cartList,
  () => {
    // 当购物车数据变化时，强制重新计算相关属性
    cartStore.selectedCount
    cartStore.selectedTotalAmount
  },
  { deep: true },
)

// 处理单个商品选择
const handleItemSelect = async (cartId: number, selected: boolean) => {
  try {
    const item = cartStore.cartList.find((item) => item.cart_id === cartId)
    if (item) {
      await cartStore.updateCartItem(cartId, item.goods_num, selected ? 1 : 0)
    }
  } catch (error) {
    console.error('更新选择状态失败:', error)
    // ElToast.error('操作失败，请稍后重试')
    // 失败时回滚状态
    await cartStore.fetchCartList()
  }
}

// 减少商品数量
const handleDecrease = async (item: CartItem) => {
  if (item.goods_num <= 1) return

  try {
    await cartStore.updateCartItem(item.cart_id, item.goods_num - 1, item.selected ? 1 : 0)
  } catch (error) {
    console.error('减少数量失败:', error)
    // ElToast.error('操作失败，请稍后重试')
  }
}

// 增加商品数量
const handleIncrease = async (item: CartItem) => {
  if (item.goods_num >= item.goods_info.goods_stock) return

  try {
    await cartStore.updateCartItem(item.cart_id, item.goods_num + 1, item.selected ? 1 : 0)
  } catch (error) {
    console.error('增加数量失败:', error)
    // ElToast.error('操作失败，请稍后重试')
  }
}

// 数量变更
const handleQuantityChange = async (item: CartItem) => {
  // 确保数量在有效范围内
  let quantity = item.goods_num
  if (quantity < 1) quantity = 1
  if (quantity > item.goods_info.goods_stock) quantity = item.goods_info.goods_stock

  if (quantity === item.goods_num) return

  try {
    await cartStore.updateCartItem(item.cart_id, quantity, item.selected ? 1 : 0)
  } catch (error) {
    console.error('更新数量失败:', error)
    // ElToast.error('操作失败，请稍后重试')
  }
}

// 移除商品
const handleRemoveItem = async (cartId: number) => {
  try {
    await ElMessageBox.confirm('确定要从购物车中移除这件商品吗？', '确认移除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await cartStore.removeCartItem(cartId)
    // ElToast.success('商品已移除')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      // ElToast.error('删除失败，请稍后重试')
    }
  }
}

// 清空购物车
const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await cartStore.clearCart()
    // ElToast.success('购物车已清空')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空购物车失败:', error)
      // ElToast.error('操作失败，请稍后重试')
    }
  }
}

// 结算
const handleCheckout = () => {
  // 直接跳转到结算页面，不进行选中商品检查
  router.push('/checkout')
}
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.clear-btn {
  padding: 6px 12px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.clear-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.cart-empty {
  text-align: center;
  padding: 80px 0;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-top: 30px;
}

.empty-img {
  width: 200px;
  height: 200px;
  margin-bottom: 30px;
  opacity: 0.7;
}

.go-shopping {
  display: inline-block;
  margin-top: 20px;
  padding: 12px 24px;
  background-color: #409eff;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.go-shopping:hover {
  background-color: #3080e0;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.empty-img {
  width: 150px;
  height: 150px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.go-shopping {
  display: inline-block;
  margin-top: 10px;
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  text-decoration: none;
  border-radius: 4px;
}

.cart-list {
  border: 1px solid #eee;
  border-radius: 4px;
}

.cart-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-checkbox {
  width: 50px;
  text-align: center;
}

.item-image {
  width: 100px;
  height: 100px;
  margin-right: 20px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-info {
  margin-bottom: 15px;
}

.current-price {
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.market-price {
  color: #999;
  text-decoration: line-through;
  font-size: 14px;
}

.item-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-control button {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background-color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.quantity-control button:hover {
  background-color: #f5f5f5;
}

.quantity-control button:active {
  background-color: #eee;
}

.quantity-control input {
  width: 50px;
  height: 30px;
  border: 1px solid #ddd;
  border-left: none;
  border-right: none;
  text-align: center;
}

.delete-btn {
  padding: 6px 12px;
  background-color: transparent;
  color: #f56c6c;
  border: 1px solid #f56c6c;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  background-color: #f56c6c;
  color: white;
}

.item-status {
  margin-top: 10px;
}

.inactive-tag {
  display: inline-block;
  padding: 2px 8px;
  background-color: #f5f5f5;
  color: #999;
  border-radius: 4px;
  font-size: 12px;
}

.stock-tag {
  display: inline-block;
  padding: 2px 8px;
  background-color: #fff3cd;
  color: #fd7e14;
  border-radius: 4px;
  font-size: 12px;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.select-all {
  display: flex;
  align-items: center;
}

.select-all input {
  margin-right: 5px;
}

.total-info {
  text-align: right;
}

.total-price {
  font-size: 18px;
  margin-top: 5px;
}

.total-price span {
  color: #f56c6c;
  font-weight: bold;
}

.checkout-btn {
  padding: 10px 20px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 20px;
  font-size: 16px;
}

.checkout-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
